<template>
  <div class="chapter-management">
    <el-row class="filters">
      <el-button type="text" @click="filterStatus('all')">全部</el-button>
      <el-button type="text" @click="filterStatus('published')">已发布</el-button>
      <el-button type="text" @click="filterStatus('draft')">草稿</el-button>
      <el-input v-model="searchQuery" placeholder="输入章节关键词" class="search-box" />
    </el-row>
    <div v-if="chapters.length === 0">
      <div>你还没有章节，点击<a @click="addChapter" href="#" class="text-link">此处</a>添加</div>
    </div>
    <div v-else class="chapter-list">
      <div v-for="(chapter, index) in filteredChapters" :key="chapter.id" class="chapter-item">
        <h3>
          <a @click="lookChapter(chapter.id)" href="#" class="text-link" style="color: black;">
            第{{ chapter.orderIndex }}章 · {{ chapter.title }}
          </a>
        </h3>
        <p class="meta">
          {{ chapter.buildTime }} · {{ chapter.views }} 浏览 · {{ chapter.likes }} 点赞 · {{ chapter.comments }} 评论 · {{ chapter.saves }} 收藏
        </p>
        <el-dropdown class="dropdown-menu" trigger="click" @command="handleCommand(chapter, $event)">
          <span class="el-dropdown-link">
            <i class="el-icon-more">...</i>
          </span>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item command="edit">编辑</el-dropdown-item>
              <el-dropdown-item command="delete">删除</el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </div>
      <div>点击<a @click="addChapter" href="#" class="text-link">此处</a>添加新章节</div>
      <el-pagination
        @current-change="handlePageChange"
        :current-page="pageNum"
        :page-size="pageSize"
        layout="prev, pager, next"
        :total="totalRecords">
      </el-pagination>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, watch } from 'vue';
import { useRoute } from 'vue-router';
import axios from 'axios';
import router from '@/router';

const route = useRoute();

// 接收父组件传递过来的 bookId prop
const props = defineProps({
  bookId: {
    type: Number,
    required: true,
  },
});
const bookId = ref(0);
// 虚拟章节数据
const chapters = ref([]);

// 分页相关数据
const pageNum = ref(1);
const pageSize = ref(10);
const totalRecords = ref(0);

// 搜索查询
const searchQuery = ref('');

// 过滤后的章节数据
const filteredChapters = computed(() => {
  return chapters.value.filter((chapter) => {
    return chapter.title.toLowerCase().includes(searchQuery.value.toLowerCase());
  });
});

// 监控 bookId 的变化并执行逻辑
watch(
  () => props.bookId,
  (newBookId) => {
    console.log(`当前书籍 ID: ${newBookId}`);
    bookId.value = newBookId;
    getChapterList();
  }
);

onMounted(() => {
  if (props.bookId) {
    console.log(`组件已挂载，接收到 bookId: ${props.bookId}`);

    bookId.value = props.bookId;

    getChapterList();
  }
});

const getChapterList = async () => {
  // 请求章节列表数据
  try {
    const res = await axios.get(`/api/chapters/summaries/${bookId.value}`, {
      params: {
        pageNum: pageNum.value,
        pageSize: pageSize.value,
      },
    });
    console.log(res);

    const data = res.data;
    chapters.value = data.data.listData;
    totalRecords.value = data.data.totalRecords;
  } catch (err) {
    console.error(err);
  }
};

// 命令处理
const handleCommand = (chapter, command) => {
  if (command === 'edit') {
    console.log(`编辑 ${chapter.title}`);
    router.push(`/chapter_update/${chapter.id}`);
  } else if (command === 'delete') {
    console.log(`删除 ${chapter.title}`);
    // 可以调用删除章节的接口，并在成功后刷新章节列表
    // deleteChapter(chapter.id);
  }
};

// 过滤章节状态
const filterStatus = (status) => {
  console.log(`过滤状态: ${status}`);
  // 可以添加逻辑根据状态过滤章节
};

const addChapter = () => {
  router.push(`/chapter_write/${bookId.value}`);
};

const lookChapter = (chapterId) => {
  router.push(`/chapter_read/${chapterId}`);
};

// 处理分页改变
const handlePageChange = (newPageNum) => {
  pageNum.value = newPageNum;
  getChapterList();
};
</script>

<style scoped>
.chapter-management {
  padding: 20px;
}

.filters {
  margin-bottom: 15px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-box {
  width: 250px;
}

.chapter-list {
  border-top: 1px solid #e8e8e8;
}

.chapter-item {
  padding: 15px 0;
  border-bottom: 1px solid #e8e8e8;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.chapter-item h3 {
  margin: 0;
  font-size: 16px;
}

.meta {
  font-size: 14px;
  color: #888;
}

.dropdown-menu {
  cursor: pointer;
}

.text-link {
  color: #409EFF;
  text-decoration: none;
}
</style>